﻿package com.shotinthedark
{
	import Nonoba.api.Connection;
	import Nonoba.api.NonobaAPI;
	
	import com.common.dataStructures2.Array2;
	import com.common.physics.CollisionDetection;
	import com.common.screens.PlayScreen;
	import com.common.utils.Math2;
	import com.common.utils.TransformEZ;
	import com.shootingGame.GamePlayManager;
	import com.shootingGame.MultiplayerGamePlayManager;
	import com.shootingGame.Player;
	import com.shootingGame.mapClasses.TileSet;
	import com.shootingGame.physics.ShooterPhysics;
	import com.shootingGame.renderableClasses.GameObject;
	import com.shootingGame.renderableClasses.PickupObject;
	import com.shootingGame.weaponsClasses.Weapon;
	import com.shootingGame.weaponsClasses.ordinance.Ordinance;
	import com.shotinthedark.maps.SITDMaps;
	import com.shotinthedark.tileSets.SampleTileSet;
	import com.shotinthedark.weapons.BasicGunWeapon;
	import com.shotinthedark.weapons.GuidedRocketWeapon;
	import com.shotinthedark.weapons.MachineGunWeapon;
	import com.shotinthedark.weapons.RocketWeapon;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
//	import flash.utils.getTimer;

	public class MultiplayerGamePlay extends MultiplayerGamePlayManager
	{
		public var maskHolder : MovieClip;
		private var viewCone : MovieClip;
		
		private var tileData : Array2;
		//private var PLAYER_DISTANCE_FROM_CENTER_TOLERANCE : Number = 5;
		
		public function MultiplayerGamePlay(playScreen:PlayScreen, connection:Connection):void
		{
			maps = new SITDMaps();
			super(playScreen, connection);
			viewRect = new Rectangle(0, 0, stageWidth, stageHeight);
			updateTimer.start();
		}
		
		override protected function loadMap(title:String):void{
			var sampleTileSet : TileSet = new SampleTileSet();
			activeMap = maps.getMap(title);
			if(activeMap){
				GamePlayManager.TILE_WIDTH = activeMap.tileWidth;//sampleTileSet.getChildAt(0).width;
				GamePlayManager.TILE_HEIGHT = activeMap.tileHeight;//sampleTileSet.getChildAt(0).height;
				GamePlayManager.MAP_NUMTILES_HORIZONTAL = activeMap.numTilesHorizontal;
				GamePlayManager.MAP_NUMTILES_VERTICAL = activeMap.numTilesVertical;
				mapHolder.addChild(activeMap.displayMap);
			}
		}
		
		override protected function initializeGame():void{
			maskHolder = playScreen.arena.maskHolder;
			player1 = new Player(true, new DummyPlayer(), null, 0, 0);
			makeSpectator(player1);
			viewCone = new ViewConeMask();
//			maskHolder.addChild(viewCone);
			desiredViewPosition = new Point(stageWidth/2.0, stageHeight/2.0);
			viewCone.x = player1.memoryX;
			viewCone.y = player1.memoryY;
			playerHolder.addChild(player1);
//			initDemo();
			super.initializeGame();
		}
		
		private function receivedUserName(response:String, username:String) : void {
			switch(response){
				case NonobaAPI.SUCCESS:{
					primaryUserName = username;
					player1.userName = primaryUserName;
					break;
				}
				case NonobaAPI.NOT_LOGGED_IN:{
					trace("The user is not logged in")
					break;
				}
				case NonobaAPI.ERROR:{
					trace("An error occurred.")
					break;
				}
			}
		}
		
		private function spawnWeaponPickup(pickupId:int, weaponType:int, xPos:int, yPos:int) : void {
			var spawnPoint : Point;
			var weaponPickup : PickupObject;
			spawnPoint = new Point(xPos, yPos);
			
			switch(weaponType){
				case 1:{
					weaponPickup = BasicGunWeapon.getPickupObject();
					break;
				}
				case 2:{
					weaponPickup = MachineGunWeapon.getPickupObject();
					break;
				}
				case 3:{
					weaponPickup = RocketWeapon.getPickupObject();
					break;
				}
				case 4:{
					weaponPickup = GuidedRocketWeapon.getPickupObject();
					break;
				}
				default:{
					break;
				}
			}
			weaponPickup.id = pickupId;
			weaponPickup.truePosition = spawnPoint;
			pickupHolder.addChild(weaponPickup);
			
//			spawnPoint = new Point (Math2.rand(0, playScreen.stage.stageWidth), Math2.rand(0, playScreen.stage.stageHeight));
//			weaponPickup = BasicGunWeapon.getPickupObject();
//			weaponPickup.truePosition = spawnPoint;
//			pickupHolder.addChild(weaponPickup);
//			
//			spawnPoint = new Point (Math2.rand(0, playScreen.stage.stageWidth), Math2.rand(0, playScreen.stage.stageHeight));
//			weaponPickup = MachineGunWeapon.getPickupObject();
//			weaponPickup.truePosition = spawnPoint;
//			pickupHolder.addChild(weaponPickup);			
//			
//			spawnPoint = new Point (Math2.rand(0, playScreen.stage.stageWidth), Math2.rand(0, playScreen.stage.stageHeight));
//			weaponPickup = GuidedRocketWeapon.getPickupObject();
//			weaponPickup.truePosition = spawnPoint;
//			pickupHolder.addChild(weaponPickup);
		}
		
		override public function onRender(evt : Event) : void {
			scrollView();
			if(viewCone){
					viewCone.rotation = player1.facing;
//					viewCone.x = x;
//					viewCone.y = y;
			}
			super.onRender(evt);
		}
		
				
		public function scrollView() : void {
			var globalPlayerPosition : Point = playerHolder.localToGlobal(new Point(player1.x, player1.y));			
			viewCone.x = globalPlayerPosition.x;
			viewCone.y = globalPlayerPosition.y;
//			var tweenSpeed:Number = 0.5;
//			if(Math2.getDistance(globalPlayerPosition.x, globalPlayerPosition.y, desiredViewPosition.x, desiredViewPosition.y) > PLAYER_DISTANCE_FROM_CENTER_TOLERANCE){
//				//GTween.defaultEase = fl.motion.easing.Sine.easeOut;			
//				var g:GTween = new GTween(mapHolder, tweenSpeed, {x:desiredViewPosition.x - player1.x, y:desiredViewPosition.y - player1.y});
//				g.play();
//				g = new GTween(playerHolder, tweenSpeed, {x:desiredViewPosition.x - player1.x, y:desiredViewPosition.y - player1.y});
//				g.play();
//				g = new GTween(pickupHolder, tweenSpeed, {x:desiredViewPosition.x - player1.x, y:desiredViewPosition.y - player1.y});
//				g.play();
//				g = new GTween(bulletHolder, tweenSpeed, {x:desiredViewPosition.x - player1.x, y:desiredViewPosition.y - player1.y});
//				g.play();
//				g = new GTween(effectsHolder, tweenSpeed, {x:desiredViewPosition.x - player1.x, y:desiredViewPosition.y - player1.y});
//				g.play();
//			}
			var newX:Number = desiredViewPosition.x - player1.x;
			var newY:Number = desiredViewPosition.y - player1.y;
			mapHolder.x = newX;
			mapHolder.y = newY;
			playerHolder.x = newX;
			playerHolder.y = newY;
			pickupHolder.x = newX;
			pickupHolder.y = newY;
			ordinanceHolder.x = newX;
			ordinanceHolder.y = newY;
			effectsHolder.x = newX;
			effectsHolder.y = newY;
			viewRect.x = player1.x - stageWidth/2.0;
			viewRect.y = player1.y - stageHeight/2.0;
		}
		
		override protected function ordinanceCollisions() : void {
			var tmpPlayer:Player;
			var globalPoint : Point;
			var ord:Ordinance;
			var positives : Array;
			var excluded : Array = new Array();
			var toDelete : Array;
			var target:GameObject;
			var targetCircleRadius:Number;
			var targetCircleCentre:Point;
			var targetCollidablePart:MovieClip;
			var i : int;
			var j : int;
			var n : int;
			var m : int;
			
			n = playerHolder.numChildren;
			for(i = 0; i < n; i++) {
				target = (playerHolder.getChildAt(i) as GameObject);
				if(target.isHitDetectionEnabled && target.canRegisterOrdinanceImpact){
					m = ordinanceHolder.numChildren;
					try{
						for(j = 0; j < m; j++) {
							ord = (ordinanceHolder.getChildAt(j) as Ordinance);
						 	if(target.isHitDetectionEnabled && target.canRegisterOrdinanceImpact && target != ord.owner){
						 		if(ShooterPhysics.detectObjectToOrdinanceCollision(target, ord)){
									target.collisionEffects.resolveCollisions();
									ord.collisionEffects.resolveCollisions();
									if(target is Player){
										tmpPlayer = target as Player;
										if(tmpPlayer.isExpired){
											trace("died " + tmpPlayer.id);
											connection.Send(MSG_EXPIRED_PLAYER, tmpPlayer.id);
										}
									}
						 		}
						 	}
						}
					}
					catch(Error){	
					}
				}

			 }
			 
			 i = 0;
			 while(i < ordinanceHolder.numChildren){
			 	if(ShooterPhysics.detectAndResolve_OrdinanceToTileCollision(ordinanceHolder.getChildAt(i) as GameObject))
			 		;
			 	i++;
			 }
		}
		
		override protected function playerCollisions() : void {
			var player:Player;
			var i : int;
			var n : int = playerList.length;
			for(i = 0; i < n; i++) {
				player = playerList[i] as Player;
//				pickupCollisions(player);
				ShooterPhysics.detectAndResolve_PlayerToTileCollision(player);
			}
		}
		
		private function pickupCollisions(player:Player) : void {
			var playerCollidable:MovieClip = player.getCollidablePart();
			var collidable_Radius:Number = playerCollidable.width/2.0;
			var collidable_CentreX:Number = player.memoryX + playerCollidable.x;
			var collidable_CentreY:Number = player.memoryY + playerCollidable.y;
			var pickupPositionX:Number;
			var pickupPositionY:Number;
			var spawnPoint : Point;
			var pickup:PickupObject;
			var itemPickedUp:GameObject;
			var i : int;
			var n : int = pickupHolder.numChildren;
			for(i = 0; i < n; i++) {
				pickup = PickupObject(pickupHolder.getChildAt(i));
				if(CollisionDetection.pointCircleIntersection(collidable_Radius, collidable_CentreX, collidable_CentreY, pickup.memoryX, pickup.memoryY)){
					//pickupHolder.removeChild(pickup);
					itemPickedUp = pickup.pickedUp();
					pickup.removeObject_FromStage();
					pickup.removeObject_FromUpdateList();
					if(itemPickedUp is Weapon){
						(itemPickedUp as Weapon).attachedTo = player;
//						connection.Send(MSG_PICKED_UP_WEAPON, (itemPickedUp as Weapon).type);
					}
					break;
//					spawnPoint = new Point (Math2.rand(0, playScreen.stage.stageWidth), Math2.rand(0, playScreen.stage.stageHeight));
//					pickup.truePosition = spawnPoint;
				}
			}
		}
		
		override protected function onMessage(e:Object){
			var message:Object = e.message;
			var tmpPlayer:Player;
			var weapon:Weapon;
			var pickupObject:PickupObject;
			var i : int;
			var n : int; 
			var j : int;
			var m : int;
			switch(message.Type){
				case MSG_WEAPON_LOCATIONS:{
					n = message.length;
					for(i = 0; i < n; i+=4) {
						spawnWeaponPickup(message.GetInt(i), message.GetInt(i+1), message.GetInt(i+2), message.GetInt(i+3));
					}
					break;
				}
				case MSG_SPAWN_WEAPON:{
					spawnWeaponPickup(message.GetInt(0), message.GetInt(1), message.GetInt(2), message.GetInt(3));
					break;
				}
				case MSG_PICKED_UP_WEAPON:{
					n = playerList.length;
					for(i = 0; i < n; i++) {
						tmpPlayer = playerList[i];
						if(tmpPlayer.id == message.GetInt(0)){
							m = pickupList.length;
							for(j = 0; j < m; j++) {
								if(pickupList[j].id == message.GetInt(2)){
									pickupObject = pickupList[j];
									weapon = pickupObject.pickedUp() as Weapon;
									weapon.attachedTo = tmpPlayer;
									break;
								}
							}
							break;
						}
					}
					break;
				}
				default:{
					super.onMessage(e);
					break;
				}
			}
		}
		
		override protected function createWeapon(type:int):Weapon{
			switch(type){
				case 1:{
					return new BasicGunWeapon();
					break;
				}
				case 2:{
					return new MachineGunWeapon();
					break;
				}
				case 3:{
					return new RocketWeapon();
					break;
				}
				case 4:{
					return new GuidedRocketWeapon();
					break;
				}
				default:{
					return null;
					break;
				}
			}
		}

		private function initDemo() : void {
			 var enemy:Player;
			 
			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;

			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;
			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;
			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;
			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;
			 enemy = spawnEnemy(); 
			 enemy.keyStates.MOUSE_X = Math2.rand(50,750);
			 enemy.keyStates.MOUSE_Y = Math2.rand(50,550);
			 new MachineGunWeapon().attachedTo = enemy;
			 enemy.keyStates.MOUSELEFT_DOWN = true;
			 enemy.isExpired = false;

		}
		
		private function spawnEnemy() : Player {
			var player:Player = new Player(false, new DummyPlayer(), null, Math2.rand(50,750), Math2.rand(50,550));
			TransformEZ.setColor(player.model.body, 0x663300);
			TransformEZ.setColor(player.model.face, 0x999900);
			playerHolder.addChild(player);
			return player;
		}

	}
}
